import axios from "axios";
import { METHOD } from "./config";
import Loading from "../components/loading/index";

const instance = axios.create({
  baseURL: "https://api.it120.cc/small4",
  timeout: 2000,
});

let loading = null;
// 添加请求拦截器
instance.interceptors.request.use(
  function(config) {
    // 在发送请求之前做些什么
    // loading = Loading.loadingServe()
    // if (localStorage.getItem("token")) {
    //   config.headers.Authorization = localStorage.getItem("token");
    // }
    return config;
  },
  function(error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  function(response) {
    // 对响应数据做点什么
    // loading.close()
    // if (response.data.msg === "无效token") {
    //   router.push({
    //     name: "login",
    //   });
    // }
    return response;
  },
  function(error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

export function request(method, url, parmas) {
  switch (method) {
    case METHOD.GET:
      return GET(url, parmas);
    case METHOD.POST:
      return POST(url, parmas);
  }
}

function GET(url, params) {
  return instance.get(url, params);
}

function POST(url, params) {
  return instance.post(url, params);
}
